import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_module/tabbar/work_space_provider.dart';
import 'package:flutter_module/tool/userManager.dart';
import 'package:flutter_module/request/NetRequest.dart';
import 'package:dio/dio.dart';
import 'work_space_model.dart';
import 'package:provider/provider.dart';
import 'work_space_provider.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';

class WorkSpaceScreen extends StatelessWidget {
  const WorkSpaceScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    return MultiProvider(providers: [
      ChangeNotifierProvider.value(value: WorkSpaceProvider())
    ],
    child: Scaffold(
        appBar: AppBar(
          title: Text('工作'),
          actions: <Widget>[
            Consumer<WorkSpaceProvider>(
              builder: (context,WorkSpaceProvider provider,clid){
                return FlatButton(
                  child: Text(provider.isEditing ? '保存':'编辑',style: TextStyle(color: Colors.white,fontSize: 17)),
                  color: Color.fromARGB(255, 46, 137, 250),
                  onPressed: (){
                    if (provider.isEditing) {
                      provider.setUserMenus(provider.userMenusList);
                      saveUserMenus(provider.userMenusList).then((val){
                        provider.editedWorkSpace();
                      });
                    } else {
                      requestUserMenus().then((val){
                        List<WorkSpaceModel> userMenus = [];
                        for (var data in val) {
                          WorkSpaceModel model = WorkSpaceModel.fromJson(data);
                          userMenus.add(model);
                        }
                        provider.editingWorkSpace(userMenus);
                      });
                    }
                  },
                );
              },
            ),
          ],
        ),
        body: FutureBuilder(
          future: requestSystemMenus(),
          builder: (context,snapshot){

            if (snapshot.hasData) {
            List<WorkSpaceModel> systemList = [];
            for (var data in snapshot.data) {
              WorkSpaceModel model = WorkSpaceModel.fromJson(data);
              systemList.add(model);
            }

            return Consumer<WorkSpaceProvider>(
                builder: (context,WorkSpaceProvider provider,clid){
                  
                  if (provider.isEditing){
                    provider.setWorkSpaceData(provider.data);
                  }else{
                    provider.setWorkSpaceData(systemList);
                  }
                  
                  return ListView.separated(
                    itemCount: provider.data.length,
                    separatorBuilder: (BuildContext context,int index){
                      return Container(
                        height: 10,
                        color: Color.fromARGB(255, 235, 239, 244),
                      );
                    },
                    itemBuilder: (BuildContext context,int index){
                      return listViewItem(provider.data[index]);
                    },
                  );
                },
              );
            } else {
                return Center(
                child: SpinKitCircle(color: Colors.lightBlue,),
              );
            }
          },
        ),
      ),
    );
  }

  Widget listViewItem(WorkSpaceModel spaceModel){
    return Container(
      child: Padding(
        padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
        child: Column(
          crossAxisAlignment : CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              spaceModel.name,
              style: TextStyle(fontWeight: FontWeight.w500,fontSize: 20),
            ),
            GridView.builder(
              padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount: spaceModel.menus.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
                crossAxisSpacing: 5,
                mainAxisSpacing:5,
                childAspectRatio:1,
              ),
              itemBuilder: (BuildContext context,int index){
                return gridViewItem(spaceModel.menus[index]);
              },
            ),
          ],
        ),
      )
    );
  }

  Widget gridViewItem(WorkSpaceDetailModel detailModel){

    return Consumer<WorkSpaceProvider>(
      builder: (context,WorkSpaceProvider provider,chid){
        return Container(
          color: Color.fromARGB(255, 247, 247, 247),
          child: Stack(
            alignment: Alignment(0.5, 0.5),
            children: <Widget>[
              Column(
                mainAxisAlignment : MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/' + detailModel.router + '.png'),
                  SizedBox(height: 10),
                  Text(detailModel.name)
                ],
              ),
              Positioned(
                right: 5,
                top: 5,
                child: InkWell(
                  onTap: (){
                    if (provider.userMenusList.length == 9 && detailModel.status == EditStatus.addition){
                      Fluttertoast.showToast(
                        msg: '最多添加9个',
                        gravity: ToastGravity.CENTER
                      );
                      return;
                    }
                    provider.additionOrDelete(detailModel);
                  },
                  child: Offstage(
                    offstage: detailModel.status == EditStatus.normal ? true : false,
                    child: detailModel.status == EditStatus.addition ? Image.asset('images/work_add.png'):Image.asset('images/work_delete.png'),
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }

  Future requestSystemMenus() async {

    print('>>>>>>>>>>>>>>网络请求<<<<<<<<<<<<');
    Response systemResponse;
    NetRequest systemDio = NetRequest();
    String url = 'menus/owner?type=SYSTEM';
    systemResponse = await systemDio.get(url);
    return systemResponse.data;
  }

  Future requestUserMenus() async {
    Response userResponse;
    NetRequest userApi = NetRequest();
    String userUrl = 'menus/owner?type=USER';
    userResponse = await userApi.get(userUrl);
    return userResponse.data;
  }

  Future saveUserMenus(List<WorkSpaceDetailModel> userMenus) async {

    List pam = [];
    userMenus.forEach((val){
      Map userMap = {};
      userMap['menuId'] = val.uuid;
      userMap['sort'] = val.sort;
      pam.add(userMap);
    });

    NetRequest userApi = NetRequest();
    String userUrl = 'menus/owner?type=USER';
    Response userResponse = await userApi.post(userUrl,data: pam);
    return userResponse.data;
  }
}